<?php
namespace app\yunda\home;

use app\yunda\model\Cash;
use app\yunda\model\User as UserModel;
use app\yunda\model\Danhao;
use app\yunda\model\Order;
use app\yunda\model\Yjrecord;
use app\yunda\model\Yhang;
use think\Db;

/**
 * 用户
 * @package app\yunda\home
 */
class User extends Base {
    // 获取列表
    public function index($row=10){
        // 查询字段
        $map = $this->getMap();
        $Address = new UserModel();
        // 自定义where查询
        $data =  $Address
            ->order('id desc')
            ->where($map)
            ->paginate($row)
            ->each(function($item){

                return $item;
            });
        $data = $data->toArray();
        return mogo_json($data);
    }
    // 保存用户信息
    public function save($openid=''){
        if(empty($openid))return mogo_error('参数错误',404);
        $row=UserModel::get(['openid'=>$openid]);
        if(empty($row))return mogo_error('用户不存在',401);
        // 第一步 过滤字段
        $data = request()->only(['name', 'phone','sex','address','home','card','birthday','email','post_code']);
        // 第二部 验证字段
        $result = $this->validate($data,'Person');
        if(true!==$result){
            return mogo_error($result,0);
        }
        $data['id']=$row['id'];
        $res = UserModel::update($data);//更新
        if(!$res)return mogo_error('系统繁忙',0);
        return mogo_json($res,'',1);
    }
    // 读取内容
    public function read($openid){
        $data = UserModel::get(['openid'=>$openid]);
        // 第一步 验存
        if(!$data) return mogo_error('用户不存在');
        if(!empty($data['member_type'])){
            $data['huiyuan']=config('member_level')[$data['member_type']];
        }else{
            $data['huiyuan']='';
        }

        // 这里可以做一些处理
        return mogo_json($data);
    }


    /**
     * 阿里云短信发送
     * @param $number 手机号码
     * @param $content  模板变量(e,g,Array('code'=>'123456'))
     * @return array    返回参数(e.g,Array('status'=>1,'msg'=>'发送成功','content'=>''))
     */
    public function send($number, $content,$openid)
    {
        $data =  plugin_action('AliyunSms','AliyunSms','sendSms',['phoneNumbers'=>$number,'templateParam'=>$content]);
        if ($data['Message'] != 'OK') {
            return ['msg' => $data['Message']];
        } else {
            $time=time();
            Db::table('dp_yd_user')->where(['openid'=>$openid])->update(['code'=>$content['code'],'yzm_time'=>$time]);
            return ['status' => 200, 'msg' => '发送成功'];
        }
    }

    /**
     * 短信验证
     * @param $mobile 手机号码
     * @param $type   验证类型(e.g,$type='login':登录)
     * @return array  参数说明(e.g,json(Array('status'=>0,'msg'=>'验证码错误','conten'=>'')))
     */
    public function verification($phone='',$openid='')
    {
        if (empty($phone)) {
            return json(['error' => '手机号码不存在'], 400);
        }
        if (empty($openid)) {
            return json(['error' => '用户不存在'], 400);
        }
        $row=Db::table('dp_yd_user')->where(['openid'=>$openid])->find();
        $row=UserModel::get(['openid'=>$openid]);
        if ($row['yzm_time'] + 60 > time()) {
            return json(['error' => '一分钟内只能发送一次短信'], 400);
        }
        $code = rand(10000, 99999);
        $rel = $this->send($phone, array('code' => $code),$openid);
        // dump($rel);die;
        if ($rel['status'] == 200) {
            return json($rel);
            //return json( '验证码发送成功');
        }
        return mogo_error($rel['msg'],404);
    }

    //登录
    public function login()
    {
        $data=request()->only(['phone','password','openid']);
        $result = $this->validate($data,'User.login');
        if(true!==$result) return mogo_error($result);
        return mogo_error('登录成功',1);
    }
    //注册
    public function register()
    {
        $data=request()->only(['phone','password','openid','code','repassword']);
        //halt($data);
        $result = $this->validate($data,'User.register');
        if(true!==$result) return mogo_error($result);
        $model=UserModel::get(['openid'=>$data['openid']]);
        $model->update([
            'id'=>$model->id,
            'phone'=>$data['phone'],
            'password'=>$data['password'],
        ]);
        return mogo_error('注册成功',1);

    }

    //韵达物流单号查询

    /**
     * @param $nu 快递单号
     * @param $com 快递类型：韵达yunda 圆通yuantong
     * @param $id 身份授权key(快递100)
     */
    public function order_search()
    {
        $param=request()->only('nu'); //快递单号，com那种快递
        if(empty($param['nu'])){
            return mogo_error('快递单号不能为空',404);
        }
        //判断运单号是否存在
        $is_danhao=Danhao::get(['order_sn'=>$param['nu'],'is_use'=>1]);
        if(empty($is_danhao)) return mogo_error('运单号不存在',404);
        //判断订单是否存在
        $is_order=Order::get(['order_id'=>$param['nu']]);
        if(empty($is_order)) return mogo_error('订单号没有订单',404);
        $kd_100=config('kd_100');
        $id=$kd_100['id'];//快递100身份授权key
        $com=$kd_100['com'];//快递类型
        $url="http://api.kuaidi100.com/api?id=".$id."&com=".$com."&nu=".$param['nu']."&show=0&muti=1&order=desc";
        $info = json_decode(get_curl($url), true);
        //halt($info);
        return mogo_json($info,'ok',1);
    }

    //获取用户openid和session_key
    public function wxLogin(){
            //code用户在微信登录的临时凭证
            $weixin=request()->only(['code','NickName','HeadUrl','bind_id']);
            if(isset($weixin['code']))$code=$weixin['code'];
            if(empty($code)){
                header("HTTP/1.1 401 Not Found");   // 如果是404 改成404即可
                header("Status: 401 Not Found");
                header('Content-type: application/json; charset=utf-8');
                exit();
            }
            $config=config('weiXin');
            //登录凭证校验接口
            $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$config['appid'].'&secret='.$config['secret']."&js_code=$code&grant_type=authorization_code";

            //code获取用户openid和session_key
            $info = json_decode(get_curl($url), true);
            if(!isset($info['session_key'])) return mogo_error($info,401);

            //判断用户是否注册，如果没有则注册用户
            $row=UserModel::get(['openid'=>$info['openid']]);
            if(empty($row)){//用户注册
                $data['openid'] =$info['openid'];
                $data['nickname']=$weixin['NickName'];
                $data['head_img']=$weixin['HeadUrl'];

                //三级分销绑定
//                if(isset($weixin['bind_id'])) $data['bind_id']=$weixin['bind_id'];
                if(!empty($weixin['bind_id'])){
                    $bind_user=UserModel::getFenXiao($weixin['bind_id']);
                    if(!$bind_user){
                        $data['one_leader']=$bind_user['one_leader'];
                        $data['two_leader']=$bind_user['two_leader'];
                        $data['three_leader']=$bind_user['three_leader'];
                    }
                }
                UserModel::create($data);
            }else{//用户已经注册
                $data=[
                    'login_time'=>time(),
                    'id'=>$row['id'],
                ];
                UserModel::update($data);
            }
            session('openid',$info['openid']);
            return json($info['openid']);
    }

    //我的分销
    public function myfenxiao()
    {
        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $arr['total']=$user['money'];//总佣金
        $arr['one']=Yjrecord::getLevelMoney($body['openid']);//一级佣金
        $arr['two']=Yjrecord::getLevelMoney($body['openid'],2);//二级佣金
        $arr['three']=Yjrecord::getLevelMoney($body['openid'],3);//三级佣金
        return mogo_json($arr,'我的分销',1);

    }

    //佣金总排行榜
    public function paihangbang()
    {
        $list =UserModel::where('money','>',0)
            ->field('nickname,head_img,money')
            ->order('money desc')
            ->select();
        return mogo_json($list,'分销排行榜',1);
    }

    //分销，我的好友
    public function friend()
    {
        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $list=UserModel::whereOr('one_leader|two_leader|three_leader','eq',$body['openid'])
            ->field('head_img,nickname')
            ->order('id desc')
            ->select();
        return mogo_json($list,'我的好友',1);
    }

    //分销，我的佣金记录
    public function yjjl()
    {
        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $list=Yjrecord::where(['openid'=>$body['openid']])
            ->field('get_money,create_time')
            ->order('id desc')
            ->select();
        foreach ($list as $v){
            $v['create_time']=format_time($v['create_time'],'Y-m-d H:i:s');
        }
        return mogo_json($list,'佣金记录',1);
    }

    //获取佣金记录
    public function myyongjin()
    {
        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $list=Yjrecord::where('openid',$body['openid'])->order('create_time')->select();
        return mogo_json($list,'佣金记录',1);
    }

    //提现申请
    public function getcash()
    {
        $body=request()->only('openid,money,type,name,phone,account');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        if(empty($body['money'])) return mogo_error('提现金额参数错误',0);

        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');

//        $yinhang=Yhang::get(['openid'=>$body['openid']]);
//        if(empty($yinhang)) return mogo_error('您还未绑定提现银行卡',0);

        if($user['money']<$body['money']) return mogo_error('提现金额不足',0);
//        $body['name']=$yinhang['name'];
//        $body['card_name']=$yinhang['card_name'];
//        $body['card']=$yinhang['card'];
        $res=Cash::create($body);
        return mogo_json($res,'申请提现',1);
    }

    //提现记录
    public function cash_record()
    {
        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $list=cash::where(['openid'=>$body['openid']])
            ->field('openid,create_time,is_tx,status,type,account,phone,money')
            ->order('id desc')->select();
        foreach ($list as &$v){
            $v['create_time']=format_time($v['create_time'],'Y-m-d H:i:s');
            $arr=['待审核','通过','拒绝'];
            $arr1=['否','是'];
            $arr2=['未知','微信','支付宝'];
            $v['status']=$arr[$v['status']];
            $v['is_tx']=$arr1[$v['is_tx']];
            $v['type']=$arr2[$v['type']];
        }
        return mogo_json($list,'提现记录',1);
    }

    //用户绑定银行卡
    public function bangka()
    {
        $body=request()->only('openid,card,card_name,name');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        if(empty($body['name'])) return mogo_error('持卡人姓名',0);
        if(empty($body['card_name'])) return mogo_error('银行名称',0);
        if(empty($body['card'])) return mogo_error('银行卡号不能为空',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $yinhang=Yhang::get(['openid'=>$body['openid']]);
        if($yinhang){
            $body['id']=$yinhang['id'];
            $res=Yhang::update($body);
        }else{
            $res=Yhang::create($body);
        }
        return mogo_json($res,'绑定银行卡',$yinhang);
    }

    //获取绑定银行卡
    public function mycard()
    {
        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $yinhang=Yhang::get(['openid'=>$body['openid']]);
        return mogo_json($yinhang,'获取绑定银行卡',1);
    }


    //分销海报
    public function poster(){

        $body=request()->only('openid');
        if(empty($body['openid'])) return mogo_error('用户参数错误',0);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $imgpath='https://'.$_SERVER['HTTP_HOST'].'/public/'.'yd'.$user['id'].'.jpg';//二维码路径
        $poster_url='https://'.$_SERVER['HTTP_HOST'].'/public/'.$user['id'].'.jpg';//海报路径

        //合成海报
        if(!file_exists($poster_url)){
            //第一步生成小程序码
            if(!file_exists($imgpath)){
                //获取access_token
                $appid='wx1a027d476a5d02c8';
                $secret='974db71e0d9585cd42c326158552ebfb';

                $token_url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
                $token_res=json_decode(get_curl($token_url), true);
                //生成小程序码
//        var_dump($token_res);die;
//        echo json_encode($token_res);die;
                if(isset($token_res['access_token'])) {
                    $code_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token_res['access_token'];

//                $page = "zh_dianc/pages/home/home";
                    $page = "pages/index/index";
//                $scene = 'storeid='.$storeid;
                    $scene =$user['id'];
                    $width = 430;
                    $post_data = '{"scene":"' . $scene . '","page":"' . $page . '","width":' . $width . '}';

                    $code_res = post_curl($code_url, $post_data);

//                var_dump($code_res);die;
//                $imgpath ='wysc' . $storeid . '.jpg';
                    file_put_contents('yd' . $user['id'] . '.jpg', $code_res);
                    $imgpath='https://'.$_SERVER['HTTP_HOST'].'/public/'.'yd'.$user['id'].'.jpg';
                }else{
                    return mogo_error('获取access_token失败',0);

                }

            }

            $foot_img_url='http://p9w4ainqa.bkt.clouddn.com/126a2e8890032b451fa9f02aeaf8942e.jpg';
            image($user['id'],'分享海报','测试海报',$imgpath,$foot_img_url);

        }
        return mogo_json($poster_url,'获取成功',1);
    }


}